include("autorun/server/exp_settings.lua")
include("autorun/server/exp_powerups.lua")

local x,y,w,h
local exp2 =  LocalPlayer():GetNWInt("Exp") 
local a = 255
local b = 255
local skkw,skkh = 570,70

if barpos == 0 then x,y,w,h = 10,40,ScrW()-20,20
elseif barpos == 1 then x,y,w,h = 35,ScrH()-120,200,20 
end

local keys = {}
if not file.Exists("exp_prefs.txt") then
	keys = {
	{38,1},
	{39,2},
	{40,3},
	{41,4},
	{42,5},
	{43,6},
	{44,7},
	{45,8},
	{46,9},
	}
	file.Write("exp_prefs.txt",glon.encode(keys))
else
	keys = glon.decode(file.Read("exp_prefs.txt"))
end

local function DrawSkillsBar(skw,skh,sky)
	surface.SetDrawColor(0,0,0,255)
	surface.DrawRect(ScrW()/2-skw/2,sky,skw,skh)
	for k,v in ipairs(skills) do
		surface.SetDrawColor(255,255,255,255)
		surface.SetTexture(surface.GetTextureID("vgui/swepicon"))
		if k <= 8 then surface.DrawTexturedRect(ScrW()/2-skw/2+(k-1)*72+5,sky+5,55,skh-20)
		draw.DrawText(v.Name.." ("..k..")","Default",ScrW()/2-skw/2+(k-1)*72+30,sky+skh-15,Color(255,255,255,255),1) end
	end
end

local CircleMat = Material( "SGM/playercircle" );
tar = LocalPlayer()
usermessage.Hook("exp_target",function(um) 
	//if tar then tar:SetColor(255,255,255,255) end
	tar = um:ReadEntity()
//	tar:SetColor(255,0,0,255)
end)
/* hook.Add("HUDPaint","DrawTarget",function()
	if tar and tar:EntIndex() != 0 then
		LocalPlayer():ChatPrint(tostring(tar:GetPos()))

		//if (tar:IsPlayer() and !tar:Alive()) then return end
		
		local trace = {}
		trace.start 	= tar:GetPos() + Vector(0,0,50)
		trace.endpos 	= trace.start + Vector(0,0,-300)
		trace.filter 	= tar
		
		local tr = util.TraceLine( trace )
		
		if not tr.HitWorld then
			tr.HitPos = tar:GetPos()
		end

		local color = Color(255,0,0,40)

		render.SetMaterial( CircleMat )
		render.DrawQuadEasy( tr.HitPos + tr.HitNormal, tr.HitNormal, 24, 24, color )
	end
end) */

// 	TARGETING SCREEN
local function TargetScreen()
	local frame = vgui.Create("DFrame")
	frame:SetPos(0,0)
	frame:SetSize(125,130)
	frame:ShowCloseButton(false)
	frame:SetTitle("")
	frame.Paint = function() 
		draw.RoundedBox(0,0,0,frame:GetWide(),frame:GetTall(),Color(0,0,0,200))
		if tar:EntIndex() == 0 then return end
		if tar:IsPlayer() then draw.DrawText(tar:Name(),"ScoreboardText",frame:GetWide()/2,1,color_white,1)
		else draw.DrawText(tar:GetClass(),"ScoreboardText",frame:GetWide()/2,1,color_white,1) end
	end

	hook.Add("Think","FrameVisible",function()
		if !tar or !frame then return end
		if frame and tar:EntIndex() == 0 then 
			frame:SetVisible(false) 
		end
		if frame and tar:EntIndex() != 0 then
			frame:SetVisible(true) 
		end
	end)
	
	local mdl = vgui.Create("DModelPanel",frame)
	mdl:SetPos(5,10)
	mdl:SetSize(frame:GetWide()-10,frame:GetTall()-15)
	mdl:SetAnimSpeed(1)
	
	local function ModelSet(mdlname)
		mdl:SetModel(mdlname)
		local prop = ents.Create("prop_physics")
		prop:SetModel(mdlname)
		if tar:IsPlayer() or tar:IsNPC() then
			function mdl:LayoutEntity(Entity)
				self:RunAnimation()
				Entity:SetAngles( Angle( 0, math.fmod(CurTime(),360)*50, 0) )
			end
		else
			function mdl:LayoutEntity(Entity)
				Entity:SetAngles( Angle( 0, math.fmod(CurTime(),360)*50, 0) )
			end
		end
		mdl:SetCamPos(prop:OBBCenter()-Vector(prop:BoundingRadius()*2,0,-prop:BoundingRadius()/13))
		mdl:SetLookAt(prop:OBBCenter()-Vector(0,0,-prop:BoundingRadius()/13))
		prop:Remove()
	end

	local changed = false
	mdl.Think = function()
		if tar then
			if tar:EntIndex() != 0 and changed == false then 
				ModelSet(tar:GetModel())
				changed = true
			elseif tar:EntIndex() == 0 or tar:GetModel() != mdl:GetEntity():GetModel() then
				changed = false
			end
		end
	end
	concommand.Add("debug",function() if frame then frame:Close() end end)
end
TargetScreen()

hook.Add("HUDPaint", "ExpHud", function()

	local exp = LocalPlayer():GetNWInt("Exp") 
	local cur = LocalPlayer():GetNWInt("CurLevel")
	local new = LocalPlayer():GetNWInt("NextLevel")
	local lvl = LocalPlayer():GetNWInt("LevelNum")
	
	if LocalPlayer():Alive() then
		
		// Draw the Experience bar
		surface.SetTexture(surface.GetTextureID("vgui/alpha-back"))
		
		surface.SetDrawColor(0,0,0,a)
		surface.DrawOutlinedRect(x,y,w,h)
	
		surface.SetDrawColor(200,0,0,a)
		surface.DrawRect(x+1.2,y+1.2,w*((exp-cur)/(new-cur))-2,h-2)
	
		draw.DrawText("Level "..lvl,"ScoreboardText",x+w/2,y-20,Color(255,255,255,a),1)
		draw.DrawText(exp.."/"..new,"ScoreboardText",x+w/2,y+1,Color(0,0,0,a),1)
		
		// Make it fade
		if exp2 != exp then a,b = 255,fadetime+CurTime() end
		
		if b < CurTime() and fadeon == 1 then a = math.Clamp(a - 150*FrameTime(),0,255) end
		
		// Draw the skills bar
		//DrawSkillsBar(skkw,skkh,25)
		
	end
	exp2 = LocalPlayer():GetNWInt("Exp")

end)

local blind,freeze,choke,curtime = false,false,false,SysTime()  
usermessage.Hook("exp_blind",function(u)   
    blind= u:ReadBool()  
    curtime = SysTime()
end )  
usermessage.Hook("exp_freeze",function(u)
	freeze = u:ReadBool()
	curtime = SysTime()
	end)
usermessage.Hook("exp_choke",function(u)
	choke = u:ReadBool()
	curtime = SysTime()
end)
hook.Add( "HUDPaint", "exp_blindpaint", function()  
    if blind then 
	
	draw.RoundedBox(0,0,0,ScrW(),ScrH(),Color(0,0,0,255))
	draw.DrawText("You were blinded for 10 seconds!","ScoreboardText",ScrW()/2,ScrH()/2,Color(255,255,255,255),1)
	draw.RoundedBox(0,ScrW()/2-200,ScrH()/2+20,400,25,color_white)
	draw.RoundedBox(0,ScrW()/2-198,ScrH()/2+22,396,21,color_black)
	draw.RoundedBox(0,ScrW()/2-198,ScrH()/2+22,396*((SysTime()-curtime)/10),21,Color(255,0,0))

	elseif freeze then
	
	draw.RoundedBox(0,0,0,ScrW(),ScrH(),Color(0,0,200,100))
	
	elseif choke then
	
	draw.RoundedBox(0,0,0,ScrW(),ScrH(),Color(200,0,0,100))
	
end
	
end )

local function GetSkillName(str)
	local ret = ""
	for k,v in ipairs(string.Explode("_",str)) do
		if k != table.Count(string.Explode("_",str)) then ret = ret ..string.upper(string.Left(v,1))..string.Right(v,string.len(v)-1).. " "
		else ret = ret ..string.upper(string.Left(v,1))..string.Right(v,string.len(v)-1) end
	end
	return ret
end

local function ExpMenu()
	local framex,framey = 600,600
	local frame = vgui.Create("DFrame")
	frame:SetSize(framex,framey)
	frame:Center()
	frame:MakePopup()
	frame:SetTitle("")
	frame.Paint = function() 
		draw.RoundedBox(3,0,0,frame:GetWide(),frame:GetTall(),Color(0,0,0,200)) 
		draw.DrawText("ExpPlus Menu","ScoreboardText",frame:GetWide()/2,5,color_white,1)
	end
	local sheet = vgui.Create("DPropertySheet",frame)
	sheet:SetPos(10,30)
	sheet:SetSize(framex-20,framey-40)
	
	local invpanel = vgui.Create("DPanel",sheet)
	invpanel:SetPos(5,5)
	invpanel:SetSize(sheet:GetWide()-10,sheet:GetTall()-10)
	invpanel.Paint = function() 
		surface.SetDrawColor(50,50,50,255)
		surface.DrawRect(0,0,invpanel:GetWide(),invpanel:GetTall())
	end
	
	local invlist = vgui.Create("DPanelList",invpanel)
	invlist:SetPos(5,5)
	invlist:SetSize(invpanel:GetWide()-10,invpanel:GetTall()-100)
	invlist:EnableHorizontal(true)
	invlist:EnableVerticalScrollbar(true)
	invlist:SetSpacing(5)
	invlist:SetPadding(5)
	
	local invbar = vgui.Create("DPanelList",invpanel)
	invbar:SetPos(5,invpanel:GetTall()-(invpanel:GetTall()-invlist:GetTall()))
	invbar:SetSize(invpanel:GetWide()-10,invpanel:GetTall()-invlist:GetTall()-5)
	invbar:SetSpacing(5)
	invbar:SetPadding(15)
	invbar:EnableHorizontal(true)
	
	local function GetXY(panel,x)
		local a,b = panel:GetPos()
		if x == true then return a else return b end
	end
	
	local selected = nil
	local function SkillPanel(sk)
		local skpanel = vgui.Create("DPanel",invlist)
		local img = vgui.Create("DImage",skpanel)
		if sk.Tex and sk.Tex != "" then img:SetImage(sk.Tex) else img:SetImage("vgui/swepicon") end
		skpanel:SetSize(invlist:GetWide()/3-10,80)
		img:SetPos(10,10)
		img:SetSize(60,60)
		function skpanel:Paint()
			draw.DrawText(GetSkillName(sk.Name),"ScoreboardText",(skpanel:GetWide()-img:GetWide()-10)/2+img:GetWide()+10,20,Color(255,255,255,255),1)
			draw.DrawText(sk.Desc,"Default",(skpanel:GetWide()-img:GetWide()-10)/2+img:GetWide()+10,40,Color(255,255,255,255),1)
			surface.SetDrawColor(255,0,0,255)
			surface.DrawOutlinedRect(0,0,skpanel:GetWide(),skpanel:GetTall())
			if selected == skpanel then
				draw.RoundedBox(0,0,0,skpanel:GetWide(),skpanel:GetTall(),Color(0,0,200,100))
			end
		end

		function skpanel:OnMousePressed()
			selected = skpanel
		end
		skpanel.id = sk.ID
		return skpanel
	end
	for _,v in ipairs(skills) do invlist:AddItem(SkillPanel(v)) end
	
	local function BindButton(text,num)
		local btn = vgui.Create("DButton",invbar)
		btn:SetSize(100,25)
		btn:SetText("Bind to "..text)
		btn.DoClick = function()
			keys[text][2] = selected.ID
			//LocalPlayer():ChatPrint("Key " .. text.. " has been bound to ID "..selected.id..".")
			file.Write("exp_prefs.txt",glon.encode(keys))
		end
		
		invbar:AddItem(btn)
	end
	for k,v in ipairs(keys) do BindButton(k,v[1]) end
	
	sheet:AddSheet("Inventory",invpanel,"gui/silkicons/wrench",false,false)
end
concommand.Add("exp_menu",ExpMenu)

local keypressed = false
hook.Add("Think","ExpKeys",function()
	for _,v in ipairs(keys) do if input.IsKeyDown(v[1])  and (input.IsKeyDown(83) or input.IsKeyDown(84)) then 
		if keypressed == false then RunConsoleCommand("exp_useskill",v[2]) 
			keypressed = true
			print(v[2])
			timer.Destroy("Key")
		else if not timer.IsTimer("Key") then timer.Create("Key",0.25,1,function() keypressed = false end) end end end 
	end 
end)
	
// Todo: Other player's EXP on screen